package ray.wx.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import ray.wx.util.MysqlUtil;

/**
 * Servlet implementation class preMenuLoadServlet
 */
@WebServlet("/preMenuLoadServlet")
public class preMenuLoadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public preMenuLoadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String strPreLevel = request.getParameter("pre_level");
		
        MysqlUtil mysql = new MysqlUtil(MysqlUtil.dbUrl, MysqlUtil.dbUser, MysqlUtil.dbPass);
        try {
			mysql.connect();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		    return;
			//throw new ServletException("Database init failed!");
		}

    	String sql = "select text_menu_id, content from text_menu where level = '" + strPreLevel + "';";        
        JSONArray jsonArray = new JSONArray();
                
        ResultSet result;
		try {
			result = mysql.get_record_value(sql);
			while (result.next()){
				String menu_id = result.getString(1);
				String content = result.getString(2);
				content = URLEncoder.encode(content,"utf-8");
								
				JSONObject jsonObject = new JSONObject(); 
				jsonObject.put("id", menu_id);
				jsonObject.put("content", content);
				
				jsonArray.add(jsonObject);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		    return;
		}
		
		PrintWriter out = response.getWriter();  
        out.print(jsonArray.toString()); 
        out.close();
        out = null;
        return;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
